package com.hk.controller;

import com.hk.commons.CommonResult;
import com.hk.model.vo.UploadImage;
import com.hk.model.vo.UploadImageVO;
import com.hk.utils.CharacterEncoding;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/2 9:46
 * @Statement: 上传图片
 */
@RestController
@RequestMapping("/upload")
public class UploadImageController {

    @PostMapping("/uploadImage")
    public UploadImageVO uploadImage(HttpServletRequest req, HttpServletResponse resp, MultipartFile file) throws IOException {
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        //        获取当前请求的协议、IP、端口
        String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort();
//        当前时间设置模板
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
//        图片存放路径
        String imageFileUrl = "/img"+"/"+date+"/";
        String uploadPath = req.getSession().getServletContext().getRealPath(imageFileUrl);
        File file1 = new File(uploadPath);
//        判断该路径是否存在或创建
        if (!file1.exists()) {
            file1.mkdirs();
        }
        System.out.println("上传文件到："+uploadPath);
        String fileName = file.getOriginalFilename();
        //                    防止图片名称重复
        String substring = UUID.randomUUID().toString().replace("-", "").substring(1,8);
        substring +="-"+fileName;
        String img = url+imageFileUrl+substring;
//        上传图片
        file.transferTo(new File(uploadPath,substring));
        if (fileName != null) {
            UploadImage uploadImage = new UploadImage(img, substring);
            UploadImageVO uploadImageVO = CommonResult.successUploadImgVO(uploadImage);
            return uploadImageVO;
        } else {
            UploadImage uploadImage = new UploadImage(img, substring);
            UploadImageVO uploadImageVO = CommonResult.errorUploadImgVO(uploadImage);
            return uploadImageVO;
        }
    }

}
